﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Data.OracleClient;
using GSLMS.Entity;
using GSLMS.Entity.DTO;
namespace GSLMS.DAL.Oracle
{
    /// <summary>
    /// 数据访问类:SYS_ROLE
    /// </summary>
    public partial class SYS_ROLE
    {
        private readonly GSLMS.Core.Loger log = new Core.Loger();
        public SYS_ROLE()
		{}

        public List<Role> GetAll()
        {
            //using (GSLMSCon obj = new GSLMSCon())
            //{
            //    return new List<Role>();
            //}
            return new List<Role>();
        }

        public List<Role> GetAll(UniversallySearchParam searchparma)
        {
            //using (GSLMSCon obj = new GSLMSCon())
            //{
            //    return new List<Role>();
            //}
            return new List<Role>();
        }

        public List<VRolePurview> GetVRolePurviewByID(long id)
        {
            //using (GSLMSCon obj = new GSLMSCon())
            //{
            //    return new List<VRolePurview>();
            //}
            return new List<VRolePurview>();

        }

        /// <summary>
        /// 提取角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Role GetByID(long id)
        {
            Role model = new Role();

            OracleParameter[] parms = new OracleParameter[]{
								new OracleParameter("P_ROLEID", id),
								new OracleParameter("p_cur", OracleType.Cursor),
								new OracleParameter("p_pcur", OracleType.Cursor)
            };

            parms[0].Direction = ParameterDirection.Input;
            parms[1].Direction = ParameterDirection.Output;
            parms[2].Direction = ParameterDirection.Output;

            DataSet ds = OracleHelper.ExecuteDataset(OracleHelper.connectionString, CommandType.StoredProcedure, "pkg_sys.proc_role_get", parms);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                model = DataRowToModel(ds.Tables[0].Rows[0]);
                if (ds.Tables.Count > 1 && ds.Tables[1].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[1];
                    string rolePrivStrs = "";
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (i != dt.Rows.Count - 1)
                            rolePrivStrs += dt.Rows[i]["MODULECODE"].ToString() + ",";
                        else
                            rolePrivStrs += dt.Rows[i]["MODULECODE"].ToString();
                    }
                    model.SelectedRoles = rolePrivStrs;
                }
            }
            else
                return null;
         
            return model;
        }

        /// <summary>
        /// 新增角色信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Add(Role model)
        {
            bool flag = false;

            OracleParameter[] parms = new OracleParameter[]{
								new OracleParameter("P_ROLEID", model.ID),
								new OracleParameter("P_ROLENAME", model.Name??""),
								new OracleParameter("P_ROLEDESC", model.Remark??""),
								new OracleParameter("P_CREATEBY", model.Creator??""),
								new OracleParameter("P_CREATEDATE", model.CreateTime),
                                new OracleParameter("returnvalue",OracleType.Number)
            };



            for (int i = 0; i < 5; i++)
            {
                parms[i].Direction = ParameterDirection.Input;
            }

            parms[5].Direction = ParameterDirection.Output;

            try
            {
                OracleConnection con = new OracleConnection(OracleHelper.connectionString);
                con.Open();
                OracleTransaction tran = con.BeginTransaction();
                OracleCommand cmd = con.CreateCommand();
                cmd.Transaction = tran;

                cmd.Parameters.Clear();
                cmd.Parameters.AddRange(parms);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "pkg_sys.proc_role_add";

                cmd.ExecuteNonQuery();
                long num = 0;

                if (parms[5].Value != DBNull.Value)
                    num = OracleHelper.ToLong(parms[5].Value.ToString());
                if (num > 0)
                {
                    flag = AddRolePriv(ref cmd, num, model.SelectedRoles);
                    if (flag)
                    {
                        tran.Commit();
                    }
                    else
                    {
                        tran.Rollback();
                    }

                }
                else
                {
                    tran.Rollback();
                }



                cmd.Dispose();
                tran.Dispose();
                con.Close();
                con.Dispose();
            }
            catch (Exception ex)
            {
                log.ExceptionHand(ex);
            }


            return flag;

        }

        /// <summary>
        /// 新增角色权限信息
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="roleID"></param>
        /// <param name="rolePrivStrs"></param>
        /// <returns></returns>
        private bool AddRolePriv(ref OracleCommand cmd, long roleID, string rolePrivStrs)
        {
            bool flag = false;
            string roleArr = rolePrivStrs.EndsWith(",") ? rolePrivStrs.Substring(0, rolePrivStrs.Length - 1) : rolePrivStrs;
            if (roleArr != null && roleArr.Split(',').Length > 0)
            {
                long id = 0;
                string opSign = "N/A";
                foreach (var moduleid in roleArr.Split(','))
                {
                    OracleParameter[] parms = new OracleParameter[]{
								new OracleParameter("P_ID",id),
								new OracleParameter("P_ROLEID", roleID),
								new OracleParameter("P_MODULECODE",moduleid),
								new OracleParameter("P_OPSIGN", opSign)};



                    for (int i = 0; i < 4; i++)
                    {
                        parms[i].Direction = ParameterDirection.Input;
                    }

                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "pkg_sys.proc_rolepriv_add";
                    cmd.Parameters.AddRange(parms);

                    try
                    {
                        int num = cmd.ExecuteNonQuery();
                        if (num != 1)
                        {
                            flag = false;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.ExceptionHand(ex);
                    }


                }
                flag = true;
            }
            else
            {
                flag = true;
            }


            return flag;
        }

        /// <summary>
        /// 编辑角色信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(Role model)
        {
            bool flag = false;

            OracleParameter[] parms = new OracleParameter[]{
								new OracleParameter("P_ROLEID", model.ID),
								new OracleParameter("P_ROLENAME", model.Name??""),
								new OracleParameter("P_ROLEDESC", model.Remark??""),
								new OracleParameter("P_CREATEBY", model.Creator??""),
								new OracleParameter("P_CREATEDATE", model.CreateTime)
            };



            for (int i = 0; i < 5; i++)
            {
                parms[i].Direction = ParameterDirection.Input;
            }

    
            try
            {
                OracleConnection con = new OracleConnection(OracleHelper.connectionString);
                con.Open();
                OracleTransaction tran = con.BeginTransaction();
                OracleCommand cmd = con.CreateCommand();
                cmd.Transaction = tran;

                cmd.Parameters.Clear();
                cmd.Parameters.AddRange(parms);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "pkg_sys.proc_role_update";


                int num = cmd.ExecuteNonQuery();

                if (num > 0)
                {
                    flag = AddRolePriv(ref cmd, model.ID, model.SelectedRoles);
                    if (flag)
                    {
                        tran.Commit();
                    }
                    else
                    {
                        tran.Rollback();
                    }

                }
                else
                {
                    tran.Rollback();
                }



                cmd.Dispose();
                tran.Dispose();
                con.Close();
                con.Dispose();
            }
            catch (Exception ex)
            {
                log.ExceptionHand(ex);
            }

            return flag;
        }
        


        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(long id)
        {
            bool flag = false;
            OracleParameter[] parms = new OracleParameter[]{
								new OracleParameter("P_ROLEID", id)};

            parms[0].Direction = ParameterDirection.Input;
 
            try
            {
                OracleHelper.ExecuteNonQuery(OracleHelper.connectionString, CommandType.StoredProcedure, "pkg_sys.proc_role_delete", parms);
                flag = true;
                
            }
            catch (Exception ex)
            {
                log.ExceptionHand(ex);
            }
            return flag;
        }

        /// <summary>
        ///DataRowToModel 
        /// </summary>
        private GSLMS.Entity.Role DataRowToModel(DataRow dr)
        {
            if (dr != null && dr.ItemArray.Length > 0)
            {

                GSLMS.Entity.Role model = new GSLMS.Entity.Role();
                if (dr["ROLEID"] != null && dr["ROLEID"].ToString() != "")
                {
                    model.ID = OracleHelper.ToLong(dr["ROLEID"].ToString());
                }
                if (dr["ROLENAME"] != null && dr["ROLENAME"].ToString() != "")
                {
                    model.Name = dr["ROLENAME"].ToString();
                }
                if (dr["ROLEDESC"] != null && dr["ROLEDESC"].ToString() != "")
                {
                    model.Remark = dr["ROLEDESC"].ToString();
                }
                if (dr["CREATEBY"] != null && dr["CREATEBY"].ToString() != "")
                {
                    model.Creator = dr["CREATEBY"].ToString();
                }
                if (dr["CREATEDATE"] != null && dr["CREATEDATE"].ToString() != "")
                {
                    model.CreateTime = DateTime.Parse(dr["CREATEDATE"].ToString());
                }
                return model;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 分页提取数据
        /// </summary>
        public  List<GSLMS.Entity.Role> GetList(GSLMS.Entity.Role searchParam)
        {
            var list = new List<GSLMS.Entity.Role>();
            DataTable dt = null;
            string tblName = "TB_SYS_ROLE";
            string sqlWhere = "";
            string strSort = "";
            int pageSize = -1;
            int pageIndex = 1;
            string strFields = "*";
            int totalCount = 0;
            int countFlag = 1;


            //是否计算总数
            countFlag = (searchParam.ReCount != null && searchParam.ReCount) ? 1 : 0;
            pageSize = (searchParam.PageSize != null && searchParam.PageSize > 0) ? searchParam.PageSize : 15;
            pageIndex = (searchParam.CurrentIndex != null && searchParam.CurrentIndex > 0) ? searchParam.CurrentIndex : 1;

            if (searchParam.Name != null && searchParam.Name.Trim() != "")
                sqlWhere += " and rolename like '%" + OracleHelper.ReplaceUnsafeSql(searchParam.Name.Trim()) + "%'";
            
            dt = OracleHelper.GetPageData(tblName, strFields, strSort, pageSize, pageIndex, countFlag, sqlWhere, out totalCount);

            searchParam.RowCount = totalCount;
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    GSLMS.Entity.Role model = new GSLMS.Entity.Role();
                    model = DataRowToModel(dt.Rows[i]);
                    list.Add(model);
                }
            }

            return list;
        }
    }
}
